package com.zjw.javaweb.hibernate.util;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;

/**
 * hibernate 工具类
 * @author zjw
 *
 */
public class HibernateUtil {

	private static final SessionFactory FACTORY = buildSessionFactory();
	
	private static SessionFactory buildSessionFactory(){
		try {
			// create the SessionFactory from hibernate.cfg.xml
			Configuration cfg = new Configuration().configure();
			return cfg.buildSessionFactory(new StandardServiceRegistryBuilder()
					.applySettings(cfg.getProperties()).build());
		} catch (Exception e) {
			System.err.println("build SessionFactory error!!!");
			e.printStackTrace();
			throw new ExceptionInInitializerError(e);
		}
	}
	
	public static SessionFactory getSessionFactory(){
		return FACTORY;
	}
	
	public static Session openSession(){
		return FACTORY.openSession();
	}
}
